let fs = require("fs");



//生成对应runtime
let scenes = fs.readdirSync("./laya/pages");
let pagesDir = fs.readdirSync("./src/pages");
console.log("dir--->", pagesDir)
for (let i in scenes) {
    if (scenes[i].indexOf("scene") != -1) {
        // let data = JSON.parse(fs.readFileSync("./laya/pages/" + scenes[i]).toString());
        if (pagesDir.indexOf(scenes[i].replace(".scene", ".ts")) != -1) {
            console.log("has-->", './laya/pages/' + scenes[i]);
            createMethods(fs.readFileSync('./src/pages/' + scenes[i].replace('.scene', '.ts')).toString(), JSON.parse(fs.readFileSync('./laya/pages/' + scenes[i]).toString()), scenes[i].replace('.scene', '.ts'));
        } else {
            console.log("不存在页面" + scenes[i] + "的runtime类----创建");
            fs.writeFileSync("./src/pages/" + scenes[i].replace(".scene", ".ts"), createNewClass(scenes[i].replace(".scene", "")));
            createMethods(fs.readFileSync('./src/pages/' + scenes[i].replace('.scene', '.ts')).toString(), JSON.parse(fs.readFileSync('./laya/pages/' + scenes[i]).toString()), scenes[i].replace('.scene', '.ts'));
        }
    }
}


function createMethods(runtimedata, scenedata, runtimename) {
    // console.log(runtimedata)
    console.log("====================", runtimename)
    if (!scenedata.props.runtime) {//runtime挂载到脚本
        scenedata.props.runtime = "pages/" + runtimename;
        fs.writeFileSync("./laya/pages/" + runtimename.replace('.ts', '.scene'), JSON.stringify(scenedata));
    }
    for (let i in scenedata.child) {
        // console.log("--->", scenedata.child[i])
        let child = scenedata.child[i];
        if (child.type == "Button") {
            if (runtimedata.indexOf(child.props.var + '.on') != -1) {
                console.log("已注册按钮 ", child.props.var)
            } else {
                console.log("未注册按钮 ", child.props.var)
                //add code here
            }
            //按钮
        } else if (child.type == "List") {

        }
    }




}

//创建新类  
function createNewClass(classname) {
    let filedata = 'import { ui } from "../ui/layaMaxUI"; \n \n';
    filedata += 'export default class ' + classname + ' extends ui.' + classname + 'UI { \n'
    filedata += '  constructor() { \n';
    filedata += '   super(); \n';
    filedata += '}  \n \n';
    filedata += '  onEnable() { \n';
    filedata += '   console.log("' + classname + ' is enable");  \n'
    filedata += ' //addcode  \n}  \n';


    filedata += '}';
    return filedata
}
